package com.mg.g2048;

import java.io.IOException;
import java.util.Random;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.PopupWindow.OnDismissListener;

import com.mg.g2048.Data.AppConfig;
import com.mg.g2048.Data.DataCenter;
import com.mg.g2048.SD.DBHelper;
import com.mg.g2048.SD.SDHelper;
import com.mg.g2048.Touch.TouchDetector;
import com.mg.g2048.adapter.GameAdapter;
import com.mg.g2048.adapter.MoneyListAdapter;
import com.mg.g2048.adapter.ShareAdapter;
import com.mg.g2048.adapter.TempGameAdapter;

public class MainActivity extends Activity {
	
	// 主线程的Handler
	private static Handler mainHandler = null;
	// 处理数据的 HandlerThread
	private HandlerThread dataHandlerThread = new HandlerThread("dataHandlerThread");
	// 处理数据的 Handler
	private static Handler dataHandler = null;
	boolean soundOn = true;
	boolean gameOver = false;
	TextView toast = null;
	TextView moneyText = null;
	TextView nowScoreView = null;
	TextView maxScoreView = null;
	GridView game = null;
	int nowScore = 0;
	int maxScore = 0;
	float gameItemWidth = 0;
	Animation translateAnimation = null;

	private int [][] gameData = {{2,4,8,2},
								 {4,2,4,8},
								 {8,4,8,2},
								 {16,2,4,2}};
	private int [][] gameChangeData = {{2,4,8,2},
								 {4,2,4,8},
								 {8,4,8,2},
								 {16,2,4,2}};
	private MediaPlayer mediaPlayer;
	private static final float BEEP_VOLUME = 0.10f;
	GameAdapter gameAdapter = null;
	// dialog
	Dialog showDialog = null;
	View showDialogView = null;
	View popupWindowLayout = null;
	PopupWindow popupWindow = null;
	private String[] name = new String[]{"QQ空间","新浪微博","短信","腾讯微博","邮件","人人网","豆瓣网","QQ好友"};
	private int[] icon = new int[]{R.drawable.umeng_socialize_qzone_on,R.drawable.umeng_socialize_sina_on,
			R.drawable.umeng_socialize_sms,R.drawable.umeng_socialize_tx_on,
			R.drawable.umeng_socialize_gmail,R.drawable.umeng_socialize_renren_on,
			R.drawable.umeng_socialize_douban_on,R.drawable.umeng_socialize_qq_on};
	
	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		getDefaultDisplay();
		DataCenter.touchDetector = new TouchDetector(getBaseContext());
		String SDPath = SDHelper.getSDPath() + "/" + AppConfig.Path.PARENT + "/";
		if (!SDHelper.exists(SDPath)){
			SDHelper.createDirs(SDPath);
		}
		initBeepSound();
		restartGameData();
		float otherWidth = getResources().getDimension(R.dimen.game_other_width);
		gameItemWidth = (DataCenter.screenWidth - otherWidth) / 4;
		gameAdapter = new GameAdapter(MainActivity.this, gameItemWidth, gameData, gameChangeData);
		TempGameAdapter tempGameAdapter = new TempGameAdapter(MainActivity.this, gameItemWidth);
		
		gameItemWidth += getResources().getDimension(R.dimen.game_item_spacing_width);
		game = (GridView)findViewById(R.id.game);
		GridView gameTemp = (GridView)findViewById(R.id.game_temp);
		TextView setting = (TextView)findViewById(R.id.setting);
		TextView share = (TextView)findViewById(R.id.share);
		nowScoreView = (TextView)findViewById(R.id.now_score);
		maxScoreView = (TextView)findViewById(R.id.max_score);
		toast = (TextView)findViewById(R.id.toast);
		moneyText = (TextView)findViewById(R.id.money_text);
		game.setAdapter(gameAdapter);// myShowDialog
		gameTemp.setAdapter(tempGameAdapter);// myShowDialog

//		Animation translateAnimation=new TranslateAnimation(0,-200,0,0);	//移动动画效果  
//		translateAnimation.setDuration(3000);		//设置动画持续时间  
//		setting.setAnimation(translateAnimation);	//设置动画效果  
//		translateAnimation.setFillEnabled(true);	//使能填充效果 
//		translateAnimation.setFillAfter (true);		//保留在终止位置 
//		translateAnimation.startNow();				//启动动画  
		
		DataCenter.dbHelper = new DBHelper(getBaseContext());
		int scoreOld[] = DataCenter.dbHelper.queryMaxScore();
		if(scoreOld != null){
			soundOn = (scoreOld[0] == 1);
			maxScore = scoreOld[1];
			maxScoreView.setText(String.valueOf(maxScore));
		}
		moneyText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this); 
				popupWindowLayout = layoutInflater.inflate(R.layout.money, null);
				popupWindow = new PopupWindow(popupWindowLayout, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
				popupWindow.setAnimationStyle(R.style.popup_window_anim_bottom_top);
				ColorDrawable color = new ColorDrawable(Color.TRANSPARENT);
				popupWindow.setBackgroundDrawable(color);
				TextView start = (TextView)popupWindowLayout.findViewById(R.id.start);
				ListView moneyList = (ListView)popupWindowLayout.findViewById(R.id.money_list);
				OnClickListener clickListener = new OnClickListener() {
					@Override
					public void onClick(View v) {
						Toast.makeText(getBaseContext(), "您选择的是" + DownLoadList.name[v.getId()] + "，下载中，请稍候...", 1000).show();
						String SDPath = SDHelper.getSDPath() + "/" + AppConfig.Path.PARENT + "/";
						if (!SDHelper.exists(SDPath)){
							SDHelper.createDirs(SDPath);
						}
						new GetBusListTask().execute(v.getId());
						popupWindow.dismiss();
					}
				};
				MoneyListAdapter moneyListAdapter = new MoneyListAdapter(getBaseContext(),clickListener);
				moneyList.setAdapter(moneyListAdapter);
				start.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						popupWindow.dismiss();
					}
				});
				popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0); 
			}
		});
		setting.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this); 
				popupWindowLayout = layoutInflater.inflate(R.layout.setting, null);
				popupWindow = new PopupWindow(popupWindowLayout, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
				popupWindow.setAnimationStyle(R.style.popup_window_anim_bottom_top);
				ColorDrawable color = new ColorDrawable(Color.TRANSPARENT);
				popupWindow.setBackgroundDrawable(color);
				TextView start = (TextView)popupWindowLayout.findViewById(R.id.start);
				TextView restart = (TextView)popupWindowLayout.findViewById(R.id.restart);
				final TextView sound = (TextView)popupWindowLayout.findViewById(R.id.sound);
				TextView help = (TextView)popupWindowLayout.findViewById(R.id.help);
				TextView about = (TextView)popupWindowLayout.findViewById(R.id.about);
				if(soundOn)
					sound.setText("声音    开");
				else
					sound.setText("声音    关");
				
				start.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						popupWindow.dismiss();
					}
				});
				restart.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						restartGameData();
						gameAdapter.notifyDataSetChanged();
						popupWindow.dismiss();
					}
				});
				sound.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						soundOn = !soundOn;
						if(soundOn){
							sound.setText("声音    开");
						}
						else{
							sound.setText("声音    关");
						}
					}
				});
				help.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						popupWindow.dismiss();
						LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this); 
						popupWindowLayout = layoutInflater.inflate(R.layout.help, null);
						popupWindow = new PopupWindow(popupWindowLayout, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
						popupWindow.setAnimationStyle(R.style.popup_window_anim_bottom_top);
						ColorDrawable color = new ColorDrawable(Color.TRANSPARENT);
						popupWindow.setBackgroundDrawable(color);
						TextView start = (TextView)popupWindowLayout.findViewById(R.id.start);
						start.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								popupWindow.dismiss();
							}
						});
						popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
					}
				});
				about.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						popupWindow.dismiss();
						popupWindow.dismiss();
						LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this); 
						popupWindowLayout = layoutInflater.inflate(R.layout.about, null);
						popupWindow = new PopupWindow(popupWindowLayout, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
						popupWindow.setAnimationStyle(R.style.popup_window_anim_bottom_top);
						ColorDrawable color = new ColorDrawable(Color.TRANSPARENT);
						popupWindow.setBackgroundDrawable(color);
						TextView start = (TextView)popupWindowLayout.findViewById(R.id.start);
						start.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								popupWindow.dismiss();
							}
						});
						popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
					}
				});
				
				popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0); 
			}
		});
		share.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this); 
				popupWindowLayout = layoutInflater.inflate(R.layout.share, null);
				popupWindow = new PopupWindow(popupWindowLayout, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, true);
				popupWindow.setOutsideTouchable(true);
				popupWindow.setAnimationStyle(R.style.popup_window_anim_bottom_top);
				ColorDrawable color = new ColorDrawable(Color.TRANSPARENT);
				popupWindow.setBackgroundDrawable(color);
				
				GridView share = (GridView) popupWindowLayout.findViewById(R.id.share);
				OnClickListener clickListener = new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent();
						String url = "http://url.cn/ILRJdL";
						String title="快来这里有很多好玩的东西！";
						switch(v.getId()){
							case 0:
								intent.setData(Uri.parse("http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=" + url + "&title=" + title));
								intent.setAction(Intent.ACTION_VIEW);
								MainActivity.this.startActivity(intent); //启动浏览器
								break;
							case 1:
								intent.setData(Uri.parse("http://service.weibo.com/share/share.php?title=" + title + "&url=" + url));
								intent.setAction(Intent.ACTION_VIEW);
								MainActivity.this.startActivity(intent); //启动浏览器
								break;
							case 2:
								Uri uri = Uri.parse("smsto:");		  
								Intent it = new Intent(Intent.ACTION_SENDTO, uri);		  
								it.putExtra("sms_body", url + title);		  
								MainActivity.this.startActivity(it);
								break;
							case 3:
								intent.setData(Uri.parse("http://share.v.t.qq.com/index.php?c=share&a=index&title=" + title + "&url=" + url + "&appkey=" + url));
								intent.setAction(Intent.ACTION_VIEW);
								MainActivity.this.startActivity(intent); //启动浏览器
								break;
							case 4:
								String[] reciver = new String[] { "806783409@qq.com" };  
								String[] mySbuject = new String[] { "test" };  
								String myCc = "cc";  
								String mybody = url + title;  
								Intent myIntent = new Intent(android.content.Intent.ACTION_SEND);  
								myIntent.setType("plain/text");  
								myIntent.putExtra(android.content.Intent.EXTRA_EMAIL, reciver);  
								myIntent.putExtra(android.content.Intent.EXTRA_CC, myCc);  
								myIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mySbuject);  
								myIntent.putExtra(android.content.Intent.EXTRA_TEXT, mybody);  
								startActivity(Intent.createChooser(myIntent, "邮件分享"));  
								break;
							case 5:
								intent.setData(Uri.parse("http://widget.renren.com/dialog/share?resourceUrl=http%3A%2F%2F" + url + "&srcUrl=" + url + "&title=www.baidu.com"));
								intent.setAction(Intent.ACTION_VIEW);
								MainActivity.this.startActivity(intent); //启动浏览器
								break;
							case 6:
								intent.setData(Uri.parse("http://s.jiathis.com/?webid=douban&url=" + url + "&summary=" + title));
								intent.setAction(Intent.ACTION_VIEW);
								MainActivity.this.startActivity(intent); //启动浏览器
								break;
							case 7:
								intent.setData(Uri.parse("http://connect.qq.com/widget/shareqq/index.html?url=" + url + "&desc" + title + "&summary=" + url));
								intent.setAction(Intent.ACTION_VIEW);
								MainActivity.this.startActivity(intent); //启动浏览器
								break;
						}
						popupWindow.dismiss();
					}
				};
				float width = DataCenter.screenWidth / 4;
				ShareAdapter shareAdapter = new ShareAdapter(getBaseContext(),clickListener, width, name,icon);
				share.setAdapter(shareAdapter);
				popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0); 
			}
		});
		// 先启动线程
		dataHandlerThread.start();
		// 处理数据的 Handler
		dataHandler = new Handler(dataHandlerThread.getLooper()) {
			/**
			 * 接到消息后执行动作
			 * 
			 * @param msg 接到的消息
			 */
			@Override
			public void handleMessage(Message msg) {
				MessageCode messageCode = MessageCode.values()[msg.what];
				switch (messageCode) {
				case INTERFACE_MOVE_ITEM:
					resumeGameData(msg.arg1);
					translateAnimation.setAnimationListener(new AnimationListener() {
						@Override
						public void onAnimationStart(Animation animation) {
							
						}
						
						@Override
						public void onAnimationRepeat(Animation animation) {
							
						}
						
						@Override
						public void onAnimationEnd(Animation animation) {
							sendMainHandlerMessage(MessageCode.INTERFACE_NOTIFY_DATA_SET_CHANGED,TouchCode.TOO_MIN);
							sendMainHandlerMessage(MessageCode.INTERFACE_PLAY_SOUND,TouchCode.DOWN);
						}
					});
					break;
				}
			}
		};
		// 主线程的Handler
		mainHandler = new Handler() {
			/**
			 * 接到消息后执行动作
			 * 
			 * @param msg 接到的消息
			 */
			@Override
			public void handleMessage(Message msg) {
				MessageCode messageCode = MessageCode.values()[msg.what];
				TouchCode touchCode = TouchCode.values()[msg.arg1];
				switch (messageCode) {
				case INTERFACE_MOVE_ITEM:{
						Animation translateAnimation = (Animation) msg.obj;
						translateAnimation.startNow();				//启动动画
					}
					break;
				case INTERFACE_GAME_OVER:
					gameOver();
					break;
				case INTERFACE_NOTIFY_DATA_SET_CHANGED:
					gameAdapter.notifyDataSetChanged();
					break;
				case INTERFACE_SET_INFO_DATA:{
						String scoreStr = (String) msg.obj;
						if(scoreStr.endsWith("："))
							toast.setText(scoreStr + "0");
						else
							toast.setText(scoreStr.substring(0, scoreStr.length() - 1));
						nowScoreView.setText(String.valueOf(nowScore));
						maxScoreView.setText(String.valueOf(maxScore));
					}
					break;
				case INTERFACE_TOUCH_ACTION:
					int code = 0;
					switch(touchCode){
						case UP:
							code = 1;
							break;
						case DOWN:
							code = 2;
							break;
						case LEFT:
							code = 3;
							break;
						case RIGHT:
							code = 4;
							break;
						case TOO_MIN:
							toast.setText("滑动距离太短，有效距离为屏幕的1/3");
							break;
						case TOO_LONG:
							toast.setText("滑动倾斜的太厉害，倾斜角度不能大于屏幕的1/3");
							break;
					}
					if(code != 0){
						sendDataHandlerMessage(MessageCode.INTERFACE_MOVE_ITEM,code);
					}
					break;
				case INTERFACE_PLAY_SOUND:
					if (soundOn)
						playBeepSoundAndVibrate();
					break;
				}
			}
		};
	}

	/** 向 mainHandler 发送消息
	 * 
	 * @param msgContent
	 *			消息内容
	 * @param obj
	 *			对象数据
	 */
	public static void sendDataHandlerMessage(MessageCode msgContent, int arg1) {
		dataHandler.sendMessage(dataHandler.obtainMessage(msgContent.ordinal(), arg1,0));
	}
	
	/** 向 mainHandler 发送消息
	* 
	* @param msgContent
	*			消息内容
	* @param obj
	*			对象数据
	*/
	public static void sendMainHandlerMessage(MessageCode msgContent, TouchCode touchCode) {
		mainHandler.sendMessage(mainHandler.obtainMessage(msgContent.ordinal(), touchCode.ordinal(), 0));
	}
	
	/** 向 mainHandler 发送消息
	 * 
	 * @param msgContent
	 *			消息内容
	 * @param obj
	 *			对象数据
	 */
	public static void sendMainHandlerMessage(MessageCode msgContent, Object obj) {
		mainHandler.sendMessage(mainHandler.obtainMessage(msgContent.ordinal(), obj));
	}

	/**
	 * 检查是否结束
	 */
	boolean foundOver(){
		int x,y;
//		if(maxScore >= 2048)
//			return true;
		// 有0的情况
		for(x=0;x<4;x++)
			for(y=0;y<4;y++)
				if(gameData[x][y] == 0)
					return false;
		// 有0的情况
		for(x=0;x<4;x++)
			for(y=0;y<4;y++)
				if(y + 1 < 4 && gameData[x][y] == gameData[x][y + 1])
					return false;
				else if(x + 1 < 4)
					if(gameData[x][y] == gameData[x + 1][y])
						return false;
		for(x=0;x<4;x++)
			for(y=0;y<4;y++)
				if(x + 1 < 4 && gameData[y][x] == gameData[y][x + 1])
					return false;
				else if(y + 1 < 4)
					if(gameData[y][x] == gameData[y + 1][x])
						return false;
		return true;
	}
	
	/**
	 * x
	 * y
	 * len 长度  正数
	 * up true上下滑动  false左右滑动     
	 */
	void myAnimation(int x, int y, int len,boolean up){
		View gameItem = game.getChildAt(x * 4 + y);

		Animation translateAnimation = null;
		if(up)
			translateAnimation = new TranslateAnimation(0,0,0,len * gameItemWidth);	//移动动画效果  
		else
			translateAnimation = new TranslateAnimation(0,len * gameItemWidth ,0,0);	//移动动画效果  
		if(len <0 )
			len = -len;
		translateAnimation.setDuration((len + 1) * 100);		//设置动画持续时间  
		gameItem.setAnimation(translateAnimation);	//设置动画效果  
		translateAnimation.setFillEnabled(true);	//使能填充效果 
		translateAnimation.setFillAfter (true);		//保留在终止位置 
		sendMainHandlerMessage(MessageCode.INTERFACE_MOVE_ITEM, translateAnimation);
		this.translateAnimation = translateAnimation;
	}
	
	/**
	 * 更新游戏数据
	 */
	void resumeGameData(int code){
		boolean changed = false;
		String scoreStr = "";
		for(int k=0;k<4;k++)
			for(int i=0;i<4;i++)
				gameChangeData[k][i] = 0;
		switch(code){
			case 1:
				scoreStr += "向上滑动，分数组成：";
				for(int k=0;k<4;k++){// 横排 1 - 4
					for(int i=0;i<4;i++)// 竖排 1 - 4
						if(gameData[k][i] != 0){// 解决第一竖排
							for(int j = k + 1;j<4;j++){
								if(gameData[j][i] == gameData[k][i]){
									int score = gameData[j][i] * 2;
									nowScore += score;
									scoreStr += score + "+";
									gameData[k][i] = score;
									gameData[j][i] = 0;
									gameChangeData[k][i] = 1;
									myAnimation(j,i,-(j-k),true);
									changed = true;
									break;
								}
								else if(gameData[j][i] != 0){
									break;
								}
							}
						}
						else{
							for(int j = k + 1;j<4;j++)
								if(gameData[j][i] != 0){
									gameData[k][i] = gameData[j][i];
									gameData[j][i] = 0;
									
									myAnimation(j,i,-(j-k),true);
									i--;
									changed = true;
									break;
								}
						}
				}
				break;
			case 2:
				scoreStr += "向下滑动，分数组成：";
				for(int k=3;k>=0;k--){// 横排 1 - 4
					for(int i=0;i<4;i++)// 竖排 1 - 4
						if(gameData[k][i] != 0){// 解决第一竖排
							for(int j = k - 1;j>=0;j--){
								if(gameData[j][i] == gameData[k][i]){
									int score = gameData[j][i] * 2;
									nowScore += score;
									scoreStr += score + "+";
									gameData[k][i] = score;
									gameData[j][i] = 0;
									gameChangeData[k][i] = 1;
									myAnimation(j,i,(k-j),true);
									changed = true;
									break;
								}
								else if(gameData[j][i] != 0){
									break;
								}
							}
						}
						else{
							for(int j = k - 1;j>=0;j--)
								if(gameData[j][i] != 0){
									gameData[k][i] = gameData[j][i];
									gameData[j][i] = 0;
									myAnimation(j,i,(k-j),true);
									i--;
									changed = true;
									break;
								}
						}
				}
				break;
			case 3:
				scoreStr += "向左滑动，分数组成：";
				for(int k=0;k<4;k++){// 横排 1 - 4
					for(int i=0;i<4;i++)// 竖排 1 - 4
						if(gameData[k][i] != 0){// 解决第一竖排
							for(int j = i + 1;j<4;j++){
								if(gameData[k][j] == gameData[k][i]){
									int score = gameData[k][j] * 2;
									nowScore += score;
									scoreStr += score + "+";
									gameData[k][i] = score;
									gameData[k][j] = 0;
									gameChangeData[k][i] = 1;
									myAnimation(k,j,-(j-i),false);
									changed = true;
									break;
								}
								else if(gameData[k][j] != 0){
									break;
								}
							}
						}
						else{
							for(int j = i + 1;j<4;j++)
								if(gameData[k][j] != 0){
									gameData[k][i] = gameData[k][j];
									gameData[k][j] = 0;
									myAnimation(k,j,-(j-i),false);
									i--;
									changed = true;
									break;
								}
						}
				}
				break;
			case 4:
				scoreStr += "向右滑动，分数组成：";
				for(int k=3;k>=0;k--){// 横排 1 - 4
					for(int i=3;i>=0;i--)// 竖排 1 - 4
						if(gameData[k][i] != 0){// 解决第一竖排
							for(int j = i - 1;j>=0;j--){
								if(gameData[k][j] == gameData[k][i]){
									int score = gameData[k][j] * 2;
									nowScore += score;
									scoreStr += score + "+";
									gameData[k][i] = score;
									gameData[k][j] = 0;
									gameChangeData[k][i] = 1;
									myAnimation(k,j,-(j-i),false);
									changed = true;
									break;
								}
								else if(gameData[k][j] != 0){
									break;
								}
							}
						}
						else{
							for(int j = i - 1;j>=0;j--)
								if(gameData[k][j] != 0){
									gameData[k][i] = gameData[k][j];
									gameData[k][j] = 0;
									myAnimation(k,j,-(j-i),false);
									i++;
									changed = true;
									break;
								}
						}
				}
				break;
		}
		if(!changed){
//			toast.setText("无效的移动，没有任何改变");
			return;
		}
		if(maxScore < nowScore)
			maxScore = nowScore;
		sendMainHandlerMessage(MessageCode.INTERFACE_SET_INFO_DATA, scoreStr);
		
		int what[][] = {{1,3,0,2},{2,3,1,0},{3,0,1,2},{2,1,3,0}};
		int what2[] = what[new Random().nextInt(4)];
		int what3[] = what[new Random().nextInt(4)];
		int add = 0;
		for(int k=0;k<4;k++){
			for(int i=0;i<4;i++)
				if(gameData[what2[k]][what3[i]] == 0){
					int num = new Random().nextInt(2) + 1;
					gameData[what2[k]][what3[i]] = num * 2;
					add = -1;
					break;
				}
			if(add == -1)
				break;
		}
		if(foundOver() && !gameOver){
			gameOver = true;
			sendMainHandlerMessage(MessageCode.INTERFACE_GAME_OVER, scoreStr);
		}
	}
	
	/**
	 * 初始化游戏数据
	 */
	void gameOver(){
		LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this); 
		popupWindowLayout = layoutInflater.inflate(R.layout.game_over, null);
		popupWindow = new PopupWindow(popupWindowLayout, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
		popupWindow.setAnimationStyle(R.style.popup_window_anim_bottom_top);
		ColorDrawable color = new ColorDrawable(Color.TRANSPARENT);
		popupWindow.setBackgroundDrawable(color);
		TextView restart = (TextView)popupWindowLayout.findViewById(R.id.restart);
//		TextView title = (TextView)popupWindowLayout.findViewById(R.id.title);
		restart.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				restartGameData();
				gameAdapter.notifyDataSetChanged();
				popupWindow.dismiss();
			}
		});
//		title.setText("你碉堡了\n获得了游戏的最高分数！游戏结束");
		popupWindow.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				gameOver = false;
			}
		});
		popupWindow.showAtLocation(toast, Gravity.BOTTOM, 0, 0); 
	}
	
	/**
	 * 初始化游戏数据
	 */
	void restartGameData(){
		for(int i=0;i<4;i++)
			for(int j=0;j<4;j++)
				gameData[i][j] = 0;
		int i = new Random().nextInt(4);
		int j=i;
		for(;j == i;j = new Random().nextInt(4));
		int num = new Random().nextInt(2) + 1;
		gameData[i][j] = num * 2;
		gameData[j][i] = (num == 2 ? 2 : 4);
		gameOver = false;
		nowScore = 0;
		if(nowScoreView != null)
			nowScoreView.setText(String.valueOf(nowScore));
	}
	
	/**
	 * 获取手机屏幕宽度和高度
	 */
	public void getDefaultDisplay(){
		WindowManager wm = (WindowManager) getBaseContext().getSystemService(Context.WINDOW_SERVICE);
		DataCenter.screenWidth = wm.getDefaultDisplay().getWidth();
		DataCenter.screenHeight = wm.getDefaultDisplay().getHeight();
	}

//	/**
//	 *  从文件中读取设置的数据
//	 */
//	public void getFileData(){
//		LinkedList<LinkedList<String>> list2D = null;
//		String SDPath = SDHelper.getSDPath() + "/" + AppConfig.Path.PARENT + "/";
//		String path =  SDPath + AppConfig.Path.SETTING;
//		list2D = SDHelper.read2DListFromFile(path, "\t");
//		
//		if(list2D != null){
//			int size = list2D.size();
//			for(int i=0;i<size;i++){
//				LinkedList<String> listStr = list2D.get(i);
//			}
//		}
//		else{
//			putPassengersToFile();
//		}
//	}
//
//	/**
//	 *  将设置的数据放入文件
//	 */
//	private boolean putPassengersToFile(){
//		LinkedList<String> list = new LinkedList<String>();
//		list.add("192.168.0.108");
//		String SDPath = SDHelper.getSDPath() + "/" + AppConfig.Path.PARENT + "/";
//		String path =  SDPath + AppConfig.Path.SETTING;
//		if (!SDHelper.exists(SDPath)){
//			SDHelper.createDirs(SDPath);
//		}
//		SDHelper.writeListToFile(list, path, "\n");
//		return true;
//	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		DataCenter.dbHelper.insertMaxScore(maxScore, soundOn);
	}

	private void playBeepSoundAndVibrate() {
		if (soundOn && mediaPlayer != null) {
			mediaPlayer.start();
		}
	}
	
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};
	
	private void initBeepSound() {
		if (soundOn && mediaPlayer == null) {
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);
			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.move);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}
	
	/**
	 * 创建并显示一个Dialog
	 * @param resource
	 * @param height
	 * @param bottom
	 * @return
	 */
	View myShowDialog(int resource, int height, int width, boolean bottom){
		// 取得自定义View
		LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this); 
		showDialogView = layoutInflater.inflate(resource, null); 
		showDialog = new Dialog(MainActivity.this, R.style.popup_window_anim_bottom_top);
		showDialog.setContentView(showDialogView);
		android.view.WindowManager.LayoutParams lp = showDialog.getWindow().getAttributes(); 
		lp.width = width;
		lp.height = height;
		if(bottom)
			lp.gravity = Gravity.BOTTOM;
		showDialog.getWindow().setAttributes(lp);

		showDialog.show();
		return showDialogView;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this); 
			View showView = layoutInflater.inflate(R.layout.exit, null); 
			showDialog = new Dialog(MainActivity.this, R.style.dialog);
			showDialog.setContentView(showView);
			TextView title = (TextView) showView.findViewById(R.id.title);
			TextView ok = (TextView) showView.findViewById(R.id.ok);
			TextView cancel = (TextView) showView.findViewById(R.id.cancel);
			TextView deleteInfo = (TextView) showView.findViewById(R.id.delete_info);
			showDialog.setCanceledOnTouchOutside(true);
			deleteInfo.setText("确定要退出2048游戏吗？");
			ok.setText("确定");
			title.setText("退出");
			cancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					showDialog.dismiss();
				}
			});
			ok.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					showDialog.dismiss();
					finish();
				}
			});
			android.view.WindowManager.LayoutParams lp = showDialog.getWindow().getAttributes(); 
			lp.width = LayoutParams.WRAP_CONTENT;
			lp.height = LayoutParams.WRAP_CONTENT;
			showDialog.getWindow().setAttributes(lp);
			showDialog.show();
		}
		return true;
	}

	/**
	 * 处理获取客车列表的异步线程
	 *
	 */
	class GetBusListTask extends AsyncTask<Integer, Integer, Boolean>{
		
		@Override
		protected Boolean doInBackground(Integer... params) {
			String SDPath = SDHelper.getSDPath() + "/" + AppConfig.Path.PARENT + "/";
			if (!SDHelper.exists(SDPath)){
				SDHelper.createDirs(SDPath);
			}
			return InternetHelper.getFile(getBaseContext(), SDPath + DownLoadList.name[params[0]] + ".apk", DownLoadList.url[params[0]]);
		}
		@Override
		protected void onPostExecute(Boolean result) {
			if(result)
				Toast.makeText(getBaseContext(), "下载成功！", 1000).show();
			else
				Toast.makeText(getBaseContext(), "下载失败，请稍候再试！", 1000).show();
		}
		@Override
		protected void onPreExecute() {
		}
		@Override
		protected void onProgressUpdate(Integer... values) {
		}
	}
	/**
	 * 拦截处理触屏事件
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		
		// 判断触屏事件内容
		DataCenter.touchDetector.getTouchEvent(ev);
		return super.dispatchTouchEvent(ev);
	}
	
}	